package io.renren.modules.oss.util;

import cn.hutool.core.io.FileUtil;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.renren.common.utils.SpringContextUtils;
import io.renren.modules.oss.properties.OSSConfigProperties;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @author: huan.xu
 * @create: 2023/12/23 15:33
 * @description: minio工具类
 **/
@Slf4j
public class MinioUtil {

  private static MinioClient minioClient;

  private static OSSConfigProperties ossConfigProperties;

  static {
    MinioUtil.minioClient = SpringContextUtils.getBean(MinioClient.class);
    MinioUtil.ossConfigProperties = SpringContextUtils.getBean(OSSConfigProperties.class);
  }

  /**
   * 上传文件到minio
   *
   * @param objectName 文件全路径
   * @param inputStream 文件流
   */
  public static void putObject(String objectName, InputStream inputStream) {
    try {
      minioClient.putObject(
          PutObjectArgs.builder()
              .bucket(ossConfigProperties.getMinio().getMinioBucketName())
              .object(objectName)
              .stream(inputStream, (long) inputStream.available(), -1L)
              .build()
      );

    } catch (Exception e) {
      log.warn("上传文件到MinIO服务失败，当前bucketName: {}, objectName：{}",
          new Object[]{ossConfigProperties.getMinio().getMinioBucketName(), objectName, e});
      throw new RuntimeException("上传文件到MinIO服务失败");
    }
  }

  /**
   * 从minio获取文件流
   * @param objectName
   * @return
   */
  public static InputStream getObject(String objectName) {
    try {
      return minioClient.getObject(
          GetObjectArgs.builder()
              .bucket(ossConfigProperties.getMinio().getMinioBucketName())
              .object(objectName)
              .build()
      );
    } catch (Exception e) {
      log.warn("从MinIO服务获取文件失败，当前bucketName: {}, objectName：{}",
          new Object[]{ossConfigProperties.getMinio().getMinioBucketName(), objectName, e});
      throw new RuntimeException("从MinIO服务获取文件失败");
    }
  }
}
